<script setup>
import {computed, nextTick, ref} from 'vue'
import Wavy from './wavy.vue';
const modelValue = defineModel()
const emit = defineEmits(['update:modelValue', 'refused', 'accept', 'over', 'cancel'])
const props = defineProps({
    config: Object
})
const isConnected = ref(false)
const vd = ref()
let localStream, clearStream

function refused() {
    close()
    emit('refused')
}
function close() {
    emit('cancel')
    emit('update:modelValue', false)
}
function over() {
    emit('update:modelValue', false)
    isConnected.value = false
    if(localStream) localStream.getTracks().forEach(track => localStream.removeTrack(track))
    if(clearStream) clearStream()
}
function end() {
    over()
    emit('over')
}
function accept() {
    emit('accept', {type: props.config.type, id: props.config.userInfo.id})
}
function setStream(stream, clear) {
    clearStream = clear
    localStream = stream
    isConnected.value = true
    nextTick(() => {
        vd.value.srcObject = stream;
        vd.value.oncanplay = () => vd.value.play()
    })
}
const isVoice = computed(() => {
    return props.config.type === 'voice' || props.config.type === 'request_voice'
})
defineExpose({
    setStream, over,
    })
</script>

<template>
    <div class="c-werbrtc-recorder c-webrtc-media" v-if="modelValue" :class="{voice: isVoice}">
        <div><img :src="config.userInfo.userHead"></div>
        <div>{{ config.userInfo.name }}</div>
        <template v-if="!isConnected">
            <div v-if="config.type==='request_voice'||config.type==='request_video'">
                <h4>{{config.type==='request_voice' ? '是否接受语音通话请求？' : '是否接受视频通话请求？'}}</h4>
                <button @click="accept">接受</button>
                <button @click="refused">拒绝</button>
            </div>
            <div v-else-if="config.type==='request_refused'">
                <h4>请求被拒绝了</h4>
                <button @click="close">关闭</button>
            </div>
            <div v-else-if="config.type==='request_cancel'">
                <h4>对方取消了通话请求</h4>
                <button @click="close">关闭</button>
            </div>
            <div v-else-if="config.type==='voice'||config.type==='video'">
                <h4>正在请求{{config.type==='voice'?'语音':'视频'}}通话...</h4>
                <button @click="close">取消</button>
            </div>
            <div v-else-if="config.type==='denied'">
                <h4>无法访问媒体设备</h4>
                <button @click="close">取消</button>
            </div>
        </template>
        <template v-else>
            <div><video ref="vd"></video></div>
            <Wavy v-if="isVoice" class="white"></Wavy>
            <button @click="end">结束通话</button>
        </template>
    </div>
</template>